﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService

Partial Class Control_Sysfuncrolesstatuspermission_Create
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
    Dim level As String = -1
#Region "Sub and Function "
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            getMenu()
        End If
    End Sub
    Protected Sub getStatus()
        Using data As New VSEntities

            Dim p = (From q In data.Status Where q.FunctionId = ddlFunctionID.SelectedValue Order By q.Title Select q).ToList
            drlStatus.DataValueField = "StatusId"
            drlStatus.DataTextField = "Title"
            drlStatus.DataSource = p
            drlStatus.DataBind()
            Dim lstItem As New ListItem("--- Chọn ---", "")
            drlStatus.Items.Insert(0, lstItem)

            'Dim curFunc = (From q In data.SysFunctions Where q.FunctionId = ddlFunctionID.SelectedValue Select q).FirstOrDefault
            'If Not curFunc Is Nothing AndAlso curFunc.IsHoSo = 1 Then
            '    drlStatus.DataValueField = "StatusId"
            '    drlStatus.DataTextField = "TitleHoSo"
            '    drlStatus.DataSource = p
            '    drlStatus.DataBind()
            'Else
            '    drlStatus.DataValueField = "StatusId"
            '    drlStatus.DataTextField = "Title"
            '    drlStatus.DataSource = p
            '    drlStatus.DataBind()
            'End If



        End Using

    End Sub
    Private Sub load_dataSource()
        Using Data As New VSEntities
            Try
             

                'Load Dropdownlist sysfunction

                'Dim _sysFunction = (From q In Data.SysFunctions Where q.IsMenu = True And q.ParentId = 0 Order By q.Sort, q.HrefName Ascending Select q.FunctionId, q.HrefName).ToList
                'For Each a In _sysFunction

                'Next
                'ddlFunctionID.DataSource = _sysFunction
                'ddlFunctionID.DataTextField = "HrefName"
                'ddlFunctionID.DataValueField = "FunctionId"
                'ddlFunctionID.DataBind()
                'ddlFunctionID.Items.Insert(0, lstItem)

                'Load Dropdownlist AuditType
                'Get Enum AuditType to dictionary
                Dim _auditDictionary As New Dictionary(Of String, Integer)
                ' Add two keys.

                _auditDictionary.Add(getRoleAudit(Cls_Common.Audit_Type.Create.ToString), Cls_Common.Audit_Type.Create)
                _auditDictionary.Add(getRoleAudit(Cls_Common.Audit_Type.Delete.ToString), Cls_Common.Audit_Type.Delete)
                _auditDictionary.Add(getRoleAudit(Cls_Common.Audit_Type.Edit.ToString), Cls_Common.Audit_Type.Edit)
                _auditDictionary.Add(getRoleAudit(Cls_Common.Audit_Type.ViewContent.ToString), Cls_Common.Audit_Type.ViewContent)

                'If hidStatus.Value = 1 Then
                '    _auditDictionary.Add(Cls_Common.Audit_Type.Submit.ToString, Cls_Common.Audit_Type.Submit)
                '    _auditDictionary.Add(Cls_Common.Audit_Type.Publish.ToString, Cls_Common.Audit_Type.Publish)
                'End If


                'create generic list with FieldName
                Dim x = From q In _auditDictionary Select AuditType = q.Key, AuditValue = q.Value
                chklstAuditnumber.DataSource = x
                chklstAuditnumber.DataTextField = "AuditType"
                chklstAuditnumber.DataValueField = "AuditValue"
                chklstAuditnumber.DataBind()
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
            End Try
        End Using
    End Sub
    Function CheckExistsRolePermission(ByVal intFunction As Integer, ByVal intRole As Integer) As Boolean
        Using Data As New VSEntities
            Dim p As List(Of SysFuncRolesStatusPermission)
            If hidStatus.Value = 1 Then
                p = (From q In Data.SysFuncRolesStatusPermissions Where q.FunctionId = intFunction And q.RoleId = intRole And q.StatusId = drlStatus.SelectedValue Select q).ToList()
            Else
                p = (From q In Data.SysFuncRolesStatusPermissions Where q.FunctionId = intFunction And q.RoleId = intRole Select q).ToList()
            End If
            If p.Count > 0 Then
                Return True
            End If
            Return False
        End Using
    End Function
    Function getRoleAudit(ByVal str As String) As String
        Select Case str
            Case "Create"
                Return "Tạo mới"
            Case "Edit"
                Return "Sửa"
            Case "Delete"
                Return "Xóa"
            Case "ViewContent"
                Return "Xem"
        End Select
        Return ""

    End Function

#End Region
#Region "Event for control "
    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Try
            Dim _auditNumber As Integer
            Dim _count As Integer = 0
            For Each item In chklstAuditnumber.Items
                If item.Selected Then
                    If _count = 0 Then
                        _auditNumber = CInt(item.Value)
                    Else
                        _auditNumber = CInt(_auditNumber) Or CInt(item.Value)
                    End If
                    _count += 1
                End If
            Next

            'neu co status
            For Each item In chkListAuditAction.Items
                If item.Selected Then
                    If _count = 0 Then
                        _auditNumber = CInt(item.Value)
                    Else
                        _auditNumber = CInt(_auditNumber) Or CInt(item.Value)
                    End If
                    _count += 1
                End If
            Next
       

            'Check data exists
            If CheckExistsRolePermission(ddlFunctionID.SelectedValue, ddlRoleid.SelectedValue) = True Then
                Excute_Javascript("Alertbox('Vai trò chức năng này đã tồn tại, vui lòng chọn vai trò chức năng khác.');", Me.Page, True)
            Else
                'save data to sysfuncrolesstatuspermission table
                'neu function ko co status 
                If hidStatus.Value = 1 Then
                    SetPermission(CInt(ddlFunctionID.SelectedValue), CInt(ddlRoleid.SelectedValue), CInt(drlStatus.SelectedValue), _auditNumber)
                    Insert_App_Log("Create Sysfuncrolesstatuspermission:" & ddlFunctionID.Text & " - " & ddlRoleid.Text & " - " & drlStatus.Text & _auditNumber & "", Function_Name.SysFuncRolesStatusPermission, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                Else
                    SetPermission(CInt(ddlFunctionID.SelectedValue), CInt(ddlRoleid.SelectedValue), 0, _auditNumber)
                    Insert_App_Log("Create Sysfuncrolesstatuspermission:" & ddlFunctionID.Text & " - " & ddlRoleid.Text & _auditNumber & "", Function_Name.SysFuncRolesStatusPermission, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                End If

                Excute_Javascript("Alertbox('Cập nhật dữ liệu thành công.');window.location ='../../Page/Sysfuncrolesstatuspermission/List.aspx';", Me.Page, True)
            End If
        Catch ex As Exception
            log4net.Config.XmlConfigurator.Configure()
            log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
        End Try
    End Sub
    Protected Sub btnHuy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Response.Redirect("List.aspx")
    End Sub
#End Region

    Protected Sub ddlFunctionID_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlFunctionID.SelectedIndexChanged
        Using Data As New VSEntities
            Dim p = (From q In Data.SysFunctions Select q Where q.FunctionId = ddlFunctionID.SelectedValue).FirstOrDefault
            If Not p Is Nothing Then
                getStatus()
                load_dataSource()
                If p.IsStatus = True Then
                    divStatus.Visible = True
                    hidStatus.Value = 1
                Else
                    divStatus.Visible = False
                    hidStatus.Value = 0
                End If
            End If
        End Using
    End Sub
    Protected Sub getMenu()
        ddlFunctionID.Items.Clear()
        Using data As New VSEntities
            Dim p As List(Of SysFunction) = (From q In data.SysFunctions Where q.IsMenu = True And q.ParentId = 0 Order By q.Sort, q.HrefName Ascending Select q).ToList
            RecursiveFillTree(p, 0)
            ddlFunctionID.Items.Insert(0, New ListItem("--- Chọn ---", "0"))

            'Load dropdowlist Role
            Dim _role = (From q In data.Roles Select q.RoleId, q.Title).ToList
            ddlRoleid.DataSource = _role
            ddlRoleid.DataTextField = "Title"
            ddlRoleid.DataValueField = "RoleID"
            ddlRoleid.DataBind()
            Dim lstItem As New ListItem("--- Chọn ---", "")
            ddlRoleid.Items.Insert(0, lstItem)

        End Using
    End Sub
    Private Sub RecursiveFillTree(ByVal dtParent As List(Of SysFunction), ByVal _parentID As Integer)
        level += 1
        'on the each call level increment 1
        Dim appender As New StringBuilder()
        For j As Integer = 0 To level - 1
            appender.Append("&nbsp;&nbsp;&nbsp;&nbsp;")
        Next
        If level > 0 Then
            appender.Append("|__")
        End If
        Using data As New VSEntities
            Dim dv As List(Of SysFunction) = (From q In data.SysFunctions Where q.IsMenu = True And q.ParentId = _parentID Order By q.Sort, q.HrefName Ascending Select q).ToList
            Dim i As Integer

            If dv.Count > 0 Then
                For i = 0 To dv.Count - 1
                    Dim itm As New ListItem(Server.HtmlDecode(appender.ToString() + dv.Item(i).HrefName.ToString()), dv.Item(i).FunctionId.ToString())
                    ddlFunctionID.Items.Add(itm)
                    RecursiveFillTree(dtParent, Integer.Parse(dv.Item(i).FunctionId.ToString()))
                Next
            End If
        End Using
        level -= 1
        'on the each function end level will decrement by 1
    End Sub

    Protected Sub drlStatus_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drlStatus.SelectedIndexChanged

        Using _data As New VSEntities
            Dim p = (From q In _data.StatusActions Where q.FunctionId = ddlFunctionID.SelectedValue And q.CurrentStatusId = drlStatus.SelectedValue Select q.Action.ActionId, q.Action.Title, q.Action.AuditNumber).ToList
            'Dim p = (From q In _data.StatusActions Where q.FunctionId = ddlFunctionID.SelectedValue And q.CurrentStatusId = drlStatus.SelectedValue Select q.ActionId).ToArray

            'Dim lstAction = (From q In _data.Actions Where p.Contains(q.ActionId) Select q).ToList





            With chkListAuditAction
                .DataSource = p
                .DataTextField = "Title"
                .DataValueField = "AuditNumber"
                .DataBind()


            End With

        End Using

    End Sub
End Class
